package com.lyn.usbfile;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import com.lyn.usbfile.databinding.ActivityUsbfileBinding;
import com.lyn.usbfile.databinding.LayoutUsbdeviceBinding;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

import me.jahnen.libaums.core.UsbMassStorageDevice;
import me.jahnen.libaums.core.fs.UsbFile;
import me.jahnen.libaums.core.fs.UsbFileInputStream;

public class UsbFileActivity extends AppCompatActivity {

    private static final String TAG = "UsbFileActivity";
    private ActivityUsbfileBinding binding;
    private FileAdapter fileAdapter;
    private UsbDeviceAdapter usbDeviceAdapter;
    private boolean isRoot;
    private Stack<UsbFile> usbFileStack;

    @SuppressLint("UseCompatLoadingForDrawables")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityUsbfileBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        usbFileStack = new Stack<>();
        binding.toolbar.setNavigationIcon(R.drawable.menu);
        binding.toolbar.setTitle("u盘文件管理器");
        binding.drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        binding.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @SuppressLint("RtlHardcoded")
            @Override
            public void onClick(View v) {
                if (isRoot) {
                    binding.drawer.openDrawer(Gravity.LEFT);
                } else {
                    UsbFile usbFile = null;
                    if (!usbFileStack.empty()) {
                        usbFileStack.pop();
                        if (!usbFileStack.empty()) {
                            usbFile = usbFileStack.peek();
                        }
                    }
                    if (usbFile == null) return;
                    if (usbFile.isRoot()) {
                        isRoot = true;
                        binding.toolbar.setNavigationIcon(R.drawable.menu);
                    } else {
                        isRoot = false;
                        binding.toolbar.setNavigationIcon(R.drawable.back);
                    }
                    ArrayList<UsbFile> usbFileArrayList = UsbFileManager.getInstance(getApplicationContext()).readUsbDirectory(usbFile);
                    fileAdapter.setUsbFileList(usbFileArrayList);
                }
            }
        });
        //绑定侧滑ui
        LayoutUsbdeviceBinding layoutUsbdeviceBinding = LayoutUsbdeviceBinding.bind(binding.navigation.getHeaderView(0));
        //初始化usb设备列表适配器
        usbDeviceAdapter = new UsbDeviceAdapter(this);
        layoutUsbdeviceBinding.usbDeviceList.setAdapter(usbDeviceAdapter);

        //初始化文件适配器
        fileAdapter = new FileAdapter(this);

        binding.fileList.setAdapter(fileAdapter);

        //获取u盘列表
        List<UsbMassStorageDevice> usbMassStorageDevices = UsbFileManager.getInstance(getApplicationContext()).getUsbMassStorageDevices();
        usbDeviceAdapter.setUsbMassStorageDevices(usbMassStorageDevices);

        //获取u盘根目录文件列表并设置到适配器
        if (usbMassStorageDevices != null && !usbMassStorageDevices.isEmpty()) {
            UsbFile rootUsbFile = UsbFileManager.getInstance(getApplicationContext()).getRootUsbFile(usbMassStorageDevices.get(0));
            if (rootUsbFile!=null){
                Log.e("long", "是否是根目录:" + rootUsbFile.isRoot());
                usbFileStack.push(rootUsbFile);
                isRoot = rootUsbFile.isRoot();
                ArrayList<UsbFile> list = UsbFileManager.getInstance(getApplicationContext()).readUsbDirectory(rootUsbFile);
                fileAdapter.setUsbFileList(list);
            }
        }

        //设置u盘插拔移除监听器
        UsbFileManager.getInstance(getApplicationContext()).setUsbListener(new USBBroadCastReceiver.UsbListener() {
            @Override
            public void insertUsb(UsbDevice usbDevice) {
                Log.e(TAG, "insertUsb");
                refresh();
            }

            @Override
            public void removeUsb(UsbDevice usbDevice) {
                Log.e(TAG, "removeUsb");
                refresh();
            }

            @Override
            public void getReadUsbPermission(UsbDevice usbDevice) {
                Log.e(TAG, "getReadUsbPermission");
                refresh();
            }

            @Override
            public void failedReadUsb(UsbDevice usbDevice) {
                Log.e(TAG, "failedReadUsb");
                refresh();
            }
        });


        //设置文件列表控件点击监听
        binding.fileList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                UsbFile usbFile = fileAdapter.getItem(position);
                //判断当前文件是否是目录
                if (usbFile.isDirectory()) {
                    isRoot = usbFile.isRoot();
                    if (usbFile.isRoot()) {
                        binding.toolbar.setNavigationIcon(R.drawable.menu);
                    } else {
                        binding.toolbar.setNavigationIcon(R.drawable.back);
                    }
                    ArrayList<UsbFile> usbFileArrayList = UsbFileManager.getInstance(getApplicationContext()).readUsbDirectory(usbFile);
                    fileAdapter.setUsbFileList(usbFileArrayList);
                    usbFileStack.push(usbFile);
                } else {
                    new Task().execute(usbFile);
                }
            }
        });

        //设置设备列表控件点击监听器
        layoutUsbdeviceBinding.usbDeviceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                UsbMassStorageDevice usbMassStorageDevice = usbDeviceAdapter.getItem(position);
                UsbFile rootUsbFile = UsbFileManager.getInstance(getApplicationContext()).getRootUsbFile(usbMassStorageDevice);
                isRoot = false;
                binding.toolbar.setNavigationIcon(R.drawable.menu);
                ArrayList<UsbFile> list = UsbFileManager.getInstance(getApplicationContext()).readUsbDirectory(rootUsbFile);
                fileAdapter.setUsbFileList(list);
                binding.drawer.closeDrawers();
            }
        });
    }

    private void refresh() {
        //获取u盘设备列表
        List<UsbMassStorageDevice> usbMassStorageDevices = UsbFileManager.getInstance(getApplicationContext()).getUsbMassStorageDevices();
        usbDeviceAdapter.setUsbMassStorageDevices(usbMassStorageDevices);
        //获取u盘根目录文件列表设置到文件列表适配器
        if (!usbMassStorageDevices.isEmpty()) {
            UsbFile rootUsbFile = UsbFileManager.getInstance(getApplicationContext()).getRootUsbFile(usbMassStorageDevices.get(0));
            usbFileStack.clear();
            usbFileStack.push(rootUsbFile);
            isRoot = rootUsbFile.isRoot();
            ArrayList<UsbFile> list = UsbFileManager.getInstance(getApplicationContext()).readUsbDirectory(rootUsbFile);
            fileAdapter.setUsbFileList(list);
        } else {
            isRoot = true;
            fileAdapter.setUsbFileList(null);
        }
        binding.toolbar.setNavigationIcon(R.drawable.menu);
    }


    private String createTempFile(UsbFile usbFile) {
        try {
            File folder = new File(getFilesDir() + "/temp");
            if (!folder.exists()) {
                folder.mkdirs();
            }
            File file = new File(folder.getAbsolutePath(), usbFile.getName());
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
            UsbFileInputStream fileInputStream = new UsbFileInputStream(usbFile);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fileInputStream.read(buffer)) != -1) {
                bufferedOutputStream.write(buffer, 0, length);
            }
            fileInputStream.close();
            bufferedOutputStream.flush();
            bufferedOutputStream.close();
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @SuppressLint("StaticFieldLeak")
    private class Task extends AsyncTask<UsbFile, Integer, String> {
        private ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = new ProgressDialog(UsbFileActivity.this);
            progressDialog.setTitle("tips");
            progressDialog.setMessage("loading......");
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();
        }

        @Override
        protected String doInBackground(UsbFile... usbFiles) {
            return createTempFile(usbFiles[0]);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (progressDialog != null) {
                progressDialog.dismiss();
            }
            Intent intent = new Intent();
            intent.putExtra("path", s);
            setResult(1, intent);
            finish();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }
}
